<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Backend\System\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use K12SSO_Factory;
use GuzzleHttp\Client;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your homes screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->middleware('guest')->except(['logout','uaclogout']);
    }

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function doRpcLogin()
    {
//        $url = request('url', route('login'));
        $url = env("APP_URL").'/login';
        Log::info($url);
        $error = '';
        $uac = $this->getUac();
        $sessid = isset($_GET['sessid']) ? $_GET['sessid'] : '';
        $user_id = $uac->doLogin($url, 'sessid');
        if ($user_id) {
            $user = User::where('user_id', $user_id)->first();
            if ($user) {
                Auth::login($user);
                /** @var \App\Services\Backend\System\UserService $userService */
                $userService = app('userService');
                $userService->editCore(['sessid' => $sessid],['user_id' => $user_id], FALSE);
                return redirect(env('APP_URL').route('homes',null,false));
            } else {
                $error = '抱歉，您的帐号不在本系统中，无法完成登录。';
            }
        } else {
            $error = $uac->getError();
        }
        return view('auth.login', ['error' => $error]);
    }

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        $uacMode = env('CENTER_UAC_MODE', '');
        if($uacMode == 'API'){
            return $this->doApiLogin();
        }else if($uacMode == 'RPC'){
            return $this->doRpcLogin();
        }
    }

    private function doApiLogin(){
        try{
            $sessid = isset($_GET['sessid']) ? $_GET['sessid'] : '';

            $uacHost = env('CENTER_UAC_HOST', '');
            $uacPort = intval(env('CENTER_UAC_PORT', '80'));
            $uacSsoPath = env('CENTER_UAC_SSO_PATH', '');
            $appKey = env('CENTER_UAC_APPKEY', '');
            $appSecret = env('CENTER_UAC_APPSECRET', '');
            $url = '';

            if ($uacPort == 443) {
                $url .= "https";
            } else {
                $url .= "http";
            }
            $url .= "://".$uacHost;
            if ($uacPort != 80 && $uacPort != 443) {
                $url .= ":" . $uacPort;
            }

            if ($sessid) { //UAC 登录完成，跳回到当前页面并附加 sessid 参数，通过此参数来获取当前登录的用户名
                $client = new Client(['verify' =>false]);

                $nowTime = date('Y-m-d H:i:s');
                $sign = md5(md5($appKey.$nowTime).$appSecret);
                $response = $client->request('POST', $url.$uacSsoPath, [
                    'form_params' => [
                        'app_key' => $appKey,
                        'time' => $nowTime,
                        'sign' => $sign,
                        'action' => 'user_isUserLogin',
                        'format' => 'json',
                        'sessid' => $sessid,
                    ]
                ]);
                //返回信息包体
                $data = json_decode($response->getBody(), TRUE );
                $error_code = $data['error_code'];
                if($error_code == 0){
                    $uuid = $data["user_uuid"];
                    $user = User::where('user_uuid', $uuid)->first();
                    if ($user) {
                        Auth::login($user);
                        return redirect(env('APP_URL').route('homes',null,false));
                    } else {
                        $error = '抱歉，您的帐号不在本系统中，无法完成登录。';
                    }
                }else{
                    $error = $data["error_message"];
                }
            }else{
                //没有 sessid 参数，或从 UAC 中获取用户名失败，跳转到 UAC 登录页面
                $site_url = request('url', env('APP_URL').route('login',null,false));
                $site_url = $this->clearUrl($site_url);
                $login_url = $url.'/platform/app/login.php?url=' . urlencode($site_url);
                header('Location: ' . $login_url);
                exit;
            }
        }catch(\Exception $e)
        {
            $error = $e->getMessage();
        }

        return view('auth.login', ['error' => $error]);
    }

    /**
     * 清理 URL 中的 sessid 参数。
     *
     * @param string $url
     * @return string
     */
    private function clearUrl($url)
    {
        return preg_replace("/(\?|&)sessid(=[^&]*)?&?/", '', $url);
    }

    /**
     * Where to redirect users after login.
     *
     * @return string
     */
    protected function redirectTo()
    {
        return env('APP_URL').route('homes',null,false);
    }

    /**
     * uac注销
     */
    public function uaclogout()
    {
        $uacHost = env('CENTER_UAC_HOST', '');
        $uacPort = intval(env('CENTER_UAC_PORT', '80'));
        $url = '';

        if ($uacPort == 443) {
            $url .= "https";
        } else {
            $url .= "http";
        }
        $url .= "://".$uacHost;
        if ($uacPort != 80 && $uacPort != 443) {
            $url .= ":" . $uacPort;
        }
        $site_url = env('APP_URL').route('apps.logout',null,false);
        $logout_url = $url.'/platform/app/logout_do.php?url=' . urlencode($site_url);
        return redirect($logout_url);
    }

    /**
     * 注销
     */
    public function logout()
    {
        $url = request('url', env('APP_URL').route('entrance',null,false));
        Auth::logout();

        return redirect($url);
    }

    /**
     * PC学生注销
     */
    public function studentlogout()
    {
        $url = request('url', env('APP_URL').route('entrance',null,false));
        Auth::guard('mobile')->logout();

        return redirect($url);
    }
}
